package com.sws.worktive;

import java.util.ArrayList;
import java.util.List;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONObject;

import android.app.ProgressDialog;
import android.content.Context;
import android.os.Bundle;
import android.support.v4.app.FragmentManager;
import android.telephony.TelephonyManager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import com.sws.worktive.sign_up_service.CustomVerificationCodeDialog;
import com.sws.worktive.sign_up_service.CustomVerificationCodeDialog.OnEnterListener;
import com.sws.worktive.sign_up_service.VerificationCodeFetcher;
import com.sws.worktive.sign_up_service.VerificationCodeFetcher.VerificationCodeReceiveListener;
import com.sws.worktive.task.ServerDownload;
import com.sws.worktive.task.ServerResponse;
import com.sws.worktive.util.Constant;
import com.sws.worktive.util.WT_Prefrences;
import com.sws.worktive.util.WorktiveUtil;

public class SignUpFragment extends BaseFragment implements OnClickListener,ServerResponse{

	LinearLayout ll_back;
	Button btn_signup;
	EditText edt_password,edt_con_password, edt_phno;
	WT_Prefrences wtprefences;
	List<NameValuePair> nameValuePairs;
	
	private boolean shouldHideProgressBar;
	private ProgressBar mProgressBar;
	
	private final String TAG_VERIFICATIONCODE_REQUEST = "tag_verification_code_request"; 
	
	//======================== API ========================
	
	public static SignUpFragment newInstance(
			FragmentManager fragmentManager,
			String fragmentTag){
		
		SignUpFragment signUpFragment = (SignUpFragment) fragmentManager.findFragmentByTag(fragmentTag);
		
		if (signUpFragment == null) {
			signUpFragment = new SignUpFragment();
			return signUpFragment;
		}
		
		return null;
	}
	

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		
		View view = inflater.inflate(R.layout.signup_screen, container, false);
		TextView txtHeader = (TextView) view.findViewById(R.id.screen_title);
		btn_signup=(Button)view.findViewById(R.id.btn_signup);
		
		btn_signup.setOnClickListener(this);
		view.findViewById(R.id.btn_vercode).setOnClickListener(this);;
		
		txtHeader.setText(getResources().getString(R.string.sign_up));
		wtprefences=new WT_Prefrences(getActivity());
		
		edt_password=(EditText)view.findViewById(R.id.edt_password);
		edt_phno=(EditText)view.findViewById(R.id.edt_phno);
		edt_con_password=(EditText)view.findViewById(R.id.edt_con_password);

		TelephonyManager tMgr = (TelephonyManager)getActivity().getSystemService(Context.TELEPHONY_SERVICE);
		String mPhoneNumber = tMgr.getLine1Number();
		if(mPhoneNumber!=null){
			edt_phno.setText("6786225652");
		}
		
		ll_back = (LinearLayout) view.findViewById(R.id.layout_back);
		ll_back.setOnClickListener(this);
		
		mProgressBar = (ProgressBar)view.findViewById(R.id.progressBarSignUp);
		if (shouldHideProgressBar) mProgressBar.setVisibility(View.GONE);
		
		hideSignUpField();
		return view;
	}
	
	private void hideProgressBar(){
		View view = getView();
		if(view != null)view.findViewById(R.id.progressBarSignUp).setVisibility(View.GONE);
		shouldHideProgressBar = true;
	}
	
	private void showProgressBar(){
		View view = getView();
		if(view != null)view.findViewById(R.id.progressBarSignUp).setVisibility(View.VISIBLE);;
		shouldHideProgressBar = false;
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
			case R.id.layout_back:
				FragmentManager fragmentManager = getActivity()
						.getSupportFragmentManager();
				fragmentManager.popBackStack();
				break;
			case R.id.btn_signup:
				
				if(edt_phno.getText().toString().length()==0){
					Toast.makeText(getActivity(), getString(R.string.valPhone), Toast.LENGTH_SHORT).show();
				}else if(edt_password.getText().toString().length()==0){
					Toast.makeText(getActivity(), getString(R.string.valpassword), Toast.LENGTH_SHORT).show();
				}else if(!edt_password.getText().toString().equals(edt_con_password.getText().toString())){
					Toast.makeText(getActivity(), getString(R.string.confirmpassword), Toast.LENGTH_SHORT).show();
				}else{
					nameValuePairs = new ArrayList<NameValuePair>();
					nameValuePairs.add(new BasicNameValuePair("phoneNumber",
							edt_phno.getText().toString()));
					nameValuePairs.add(new BasicNameValuePair("password",
							edt_password.getText().toString().trim()));
					nameValuePairs.add(new BasicNameValuePair("devapipassword",
							Constant.PASSWORD_VALUE));
	
					((DrawerFragment) getActivity()).mProgressDialog = ProgressDialog
							.show(getActivity(), "", getActivity().getResources()
									.getString(R.string.waitregistering));
					ServerDownload serverDownload = new ServerDownload(
							getActivity(), SignUpFragment.this,
							Constant.SIGNUP_FRAGMENT);
					serverDownload.execute(nameValuePairs);
					
				}
				
				break;
			case R.id.btn_vercode:
				getVerificationCode(v);
				break;
		}
	}
	
	private void getVerificationCode(final View view){
		
		if (edt_phno.getText().toString().length() < 10) {
			Toast.makeText(getActivity(), getActivity().getString(R.string.incorrect_phone_number_length), Toast.LENGTH_SHORT).show();
			return;
		}
		
		if (!WorktiveUtil.isNumeric(edt_phno.getText().toString())) {
			Toast.makeText(getActivity(), getActivity().getString(R.string.incorrect_phone_number_format), Toast.LENGTH_SHORT).show();
			return;
		}
		
		view.setEnabled(false);
		showProgressBar();
		(new VerificationCodeFetcher(getActivity())).fetchJobs(edt_phno.getText().toString(),TAG_VERIFICATIONCODE_REQUEST, new VerificationCodeReceiveListener() {
			
			@Override
			public void onVerificationCodeReceived(final String verificationCode) {
				if (verificationCode != null) {
					handleVerificationCodeReceive(verificationCode);
				}
				view.setEnabled(true);
				hideProgressBar();
			}
		});
	}
	
	private void handleVerificationCodeReceive(final String verificationCode){
		Toast.makeText(getActivity(), verificationCode, Toast.LENGTH_LONG).show();
		final String fragmentTag = "verificationFragmentTag";
		CustomVerificationCodeDialog verificationCodeDialog = CustomVerificationCodeDialog.newInstance(getActivity().getSupportFragmentManager(), fragmentTag, new OnEnterListener() {
			
			@Override
			public void onEnter(CustomVerificationCodeDialog verificationCodeDialog) {
				if(verificationCodeDialog.editText.getText().toString().equals(verificationCode)){
					Toast.makeText(getActivity(), getActivity().getString(R.string.verify_code_success), Toast.LENGTH_SHORT).show();
					showSignUpField();
				}else {
					Toast.makeText(getActivity(), getActivity().getString(R.string.verification_code_incorrect_message), Toast.LENGTH_SHORT).show();
				}
				verificationCodeDialog.dismiss();
			}
		});
		if (verificationCodeDialog != null) {
			verificationCodeDialog.show(getActivity().getSupportFragmentManager(), fragmentTag);
		}
	}
	
	@Override
	public void httpResponse(JSONObject jsonObject, String requestTag) {

		try {
			if (jsonObject != null && jsonObject instanceof JSONObject) {
				int status = jsonObject.getInt("status");
				if (status == 1) {
					if(((DrawerFragment) getActivity()).mProgressDialog!=null)
						((DrawerFragment) getActivity()).mProgressDialog.dismiss();
					
					Toast.makeText(getActivity(),
							jsonObject.getString("message"), Toast.LENGTH_SHORT)
							.show();
					JSONObject userObj = jsonObject.getJSONObject("user");
					if (userObj != null && userObj instanceof JSONObject) {
						int phoneNumber = userObj.getInt("phoneNumber");
						String token = userObj.getString("token");
						wtprefences.setToken(token);
						wtprefences.setPhonenumber(phoneNumber);
					}
					((DrawerFragment)getActivity()).addFragment(0);
					getActivity().getSupportFragmentManager().popBackStack(null, FragmentManager.POP_BACK_STACK_INCLUSIVE);
				}else{
					if(((DrawerFragment) getActivity()).mProgressDialog!=null)
						((DrawerFragment) getActivity()).mProgressDialog.dismiss();
					
					Toast.makeText(getActivity(),
							jsonObject.getString("message"), Toast.LENGTH_SHORT)
							.show();
				}
			}
		} catch (Exception ex) {

		}
	};
	
	//WARNING: should only be call after view
	private void hideSignUpField(){
		edt_password.setVisibility(View.GONE);
		edt_con_password.setVisibility(View.GONE);
		btn_signup.setVisibility(View.GONE);
	}
	
	private void showSignUpField(){
		edt_password.setVisibility(View.VISIBLE);
		edt_con_password.setVisibility(View.VISIBLE);
		btn_signup.setVisibility(View.VISIBLE);
	}

}
